﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.PrintService;
using CoreShop.Services;
using CoreShop.Services.Services.System;
using FastMember;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;

namespace CoreShop.App
{
    public partial class frmBalanceInfo : BaseForm
    {
        public ReportBalance reportBalance = null;
        public frmBalanceInfo(ReportBalance _reportBalance)
        {
            InitializeComponent();
            reportBalance = _reportBalance;
        }

        private void FrmEditInputs_Load(object sender, EventArgs e)
        {
            SetMemberInfo();
        }

        private void SetMemberInfo()
        {
            foreach (Control ctr in this.FindForm().Controls)
            {
                if (ctr is Label)
                {
                    Label lb = ctr as Label;
                    if (CommFunc.ConvertToString(lb.Tag) == "field")
                    {
                        lb.Text = "";
                    }
                }
            }
            if ((reportBalance != null) && (reportBalance.id > 0))
            {
                ControlsDataBinding.ValueBind(reportBalance, this);
                memo.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.MemberStatus>(reportBalance.status.ObjToInt(0));
                if ((reportBalance.type == (int)GlobalEnumVars.UserBalanceTypes.Deposit)
                    || (reportBalance.type == (int)GlobalEnumVars.UserBalanceTypes.DepositRefund))
                {
                    btnPrint.Visible = true;
                }
                if ((reportBalance.type == (int)GlobalEnumVars.UserBalanceTypes.Deposit)
                    && (reportBalance.status == (int)GlobalEnumVars.BalanceStatus.IsCheck))
                {
                    btnRefund.Visible = true;
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async Task<bool> checkMemberAmountAsync(string vipNo, corecmsuserbalance balance)
        {
            try
            {
                ShowWaitForm();
                var corecmsuser = await MemberApiUtil.GetListVipInfo(vipNo);
                if (corecmsuser == null)
                {
                    HideWaitForm();
                    UIMessageTip.ShowError("服务器访问错误!");
                    return false;
                }

                if (balance.money > Convert.ToDecimal(corecmsuser.balance))
                {
                    HideWaitForm();
                    UIMessageTip.ShowError("当前会员余额不足!无法退款！", floating: false, point: DialogTool.SCREENCENTER);
                    return false;
                }
                var refundBalance = new corecmsuserbalanceServices().AsQueryable().Where(p => p.sourceId == balance.id).ToList();
                if (refundBalance.Any())
                {
                    HideWaitForm();
                    UIMessageTip.ShowError("当前会员充值已退款，不能重复退！", floating: false, point: DialogTool.SCREENCENTER);
                    return false;
                }
                return true;
            }
            catch { }
            finally
            {
                HideWaitForm();
            }
            return false;            
        }

        private async void btnRefund_Click(object sender, EventArgs e)
        {
            if (AppConstVars.classId == 0)
            {
                ProcessUtil.GetClassData(AppConstVars.sysUser.id);
                if (AppConstVars.classId == 0)
                {
                    UIMessageBox.Show("当前用户没有当班,无法退款", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
            }

            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isUserDepositRefund, 0)) return;
            
            var balanceServices = new corecmsuserbalanceServices();
            var soureceBalance = balanceServices.GetById(reportBalance.id);
            var balance = balanceServices.GetById(reportBalance.id);
            if (soureceBalance == null)
            {
                UIMessageBox.Show("未找到要退款的会员充值订单！。", "会员充值退款出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            if (soureceBalance.type != (int)GlobalEnumVars.UserBalanceTypes.Deposit)
            {
                UIMessageBox.Show("该订单不能退款！。", "会员充值退款出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            var userId = CommFunc.ConvertToBigInt(soureceBalance.userId);
            var member = new corecmsuserServices().GetById(userId);
            if (member == null)
            {
                UIMessageBox.Show("未找到相应的会员资料！。", "会员充值退款出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }

            bool checkMember = await checkMemberAmountAsync(member.mobile, soureceBalance);

            if (!checkMember) return;

            if (!ShowAskDialog("确认要对该会员充值订单进行退款吗？")) return;

            if (soureceBalance.paymentId == (int)GlobalEnumVars.Payment.alipay
            || soureceBalance.paymentId == (int)GlobalEnumVars.Payment.wechatpay
            || soureceBalance.paymentId == (int)GlobalEnumVars.Payment.paymix
            || soureceBalance.paymentId == (int)GlobalEnumVars.Payment.unionPay)
            {
                var refundPayTime = AppConstVars.systemsetup.refundPayTime;
                DateTime dPOSTime = soureceBalance.createTime;
                DateTime dDateNow = DateTime.Now;
                TimeSpan timeSpan = dDateNow - dPOSTime;
                double hPosPayTime = timeSpan.TotalMinutes;
                if ((hPosPayTime < refundPayTime) && (refundPayTime > 0))
                {
                    string msg = "";
                    var orderPayment = new OrderPaymentPost()
                    {
                        orderId = soureceBalance.paymentCode.ToString(),
                        payAmount = soureceBalance.money - soureceBalance.giftAmount
                    };
                    bool bResult = PaymentUtil.SetRefundMobilePay(orderPayment, ref msg);
                    if (!bResult)
                    {
                        UIMessageBox.Show(msg, "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                        return;
                    }
                }
                else
                {
                    UIMessageBox.Show("有移动支付的单据，必须在规定时间内退单！。", "移动支付退款出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
            }

            long sourceId = CommFunc.ConvertToBigInt(soureceBalance.id);
                        
            //decimal amount = - (soureceBalance.money - soureceBalance.giftAmount) ;
            decimal amount = -soureceBalance.money;
            balance.id = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId()); 
            balance.money = amount;
            balance.realAmount = -(soureceBalance.money - soureceBalance.giftAmount);
            balance.giftAmount = -soureceBalance.giftAmount;
            balance.orderId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.会员充值消费编号);
            balance.type = (int)GlobalEnumVars.UserBalanceTypes.DepositRefund;
            balance.memo = "会员充值退款";
            balance.classId = AppConstVars.classId;
            balance.sourceId = sourceId;
            balance.vipNo = member.mobile;
            if (balanceServices.InsertAsync(balance))
            {                
                PosOrderHeadDto postData = new OrderBusiness().GetUserDepositData(balance, AppConstVars.sysUser, AppConstVars.sysStore, AppConstVars.classNumber, (int)OrderBillType.Deposit);
                postData.posOrderHeadId = null;
                postData.amountDiscount = postData.amountOrder;
                postData.amountBalance = postData.amountOrder;
                var res = await OrderApiUtil.SendOrderAsync(postData);

                if (res.code == 1 || res.code == 200)
                {
                    member.balance = balance.balance;
                    member.giftBalance = balance.giftBalance;
                    new corecmsuserServices().UpdateAsync(member);
                    balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                    balance.status = (int)GlobalEnumVars.BalanceStatus.SuccessRefund;
                    balance.paymentTime = DateTime.Now;
                    balanceServices.UpdateAsync(balance);
                    balanceServices.Update(a => new corecmsuserbalance()
                    {
                        status = (int)GlobalEnumVars.BalanceStatus.IsRefund,
                    }, a => a.id == sourceId);
                    UIMessageBox.Show("会员充值退款成功！。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    UIMessageBox.Show(res.msg, "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
            }
            else
            {
                UIMessageBox.Show("会员充值退款失败", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                return;
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            var balanceServices = new corecmsuserbalanceServices();
            var balance = balanceServices.GetById(reportBalance.id);
            if (balance == null)
            {
                UIMessageBox.Show("未找到要打印会员充值订单！。", "会员充值打印出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            var userId = CommFunc.ConvertToBigInt(balance.userId);
            var member = new corecmsuserServices().GetById(userId);
            if (member == null)
            {
                UIMessageBox.Show("未找到相应的会员资料！。", "会员充值打印出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            balance.realAmount = balance.money - balance.giftAmount;
            var corecmspayments = new corecmspaymentsService().GetById(balance.paymentId);
            if (corecmspayments != null) balance.payName = corecmspayments.name;
            var sysuser = new sysuserServices().GetById(balance.sysUserId);
            if (sysuser != null) balance.sysUserName = sysuser.userName;
            new PrintServices().SetUserDepositBill(balance, member, false);
        }


        public async Task<AsyncReturnModel> CashRechargeRefund(corecmsuserbalance balance, corecmsuser member)
        {
            OrderBusiness orderBusiness = new OrderBusiness();
            var orderClass = new corecmsfoodorderclassServices().GetById(AppConstVars.classId);
            //本金+赠金
            //decimal decAll = dec + decZ;
            string tableid = YitIdHelper.NextId().ToString();
            string billNo = YitIdHelper.NextId().ToString();
            //支付金额
            decimal decPrice = balance.money - balance.giftAmount;
            decimal decZ = balance.giftAmount;
            //主订单
            var HeadOrderInfo = orderBusiness.CreateTopUpHeadOder(tableid, -balance.money, -balance.money, decZ, billNo, AppConstVars.sysStore, member, AppConstVars.sysUser, orderClass, (int)OrderBillType.Deposit, balance.id.ToString());
            //商品信息
            //List<PosOrderLineDto> lineDtos = orderBusiness.CreateLineOrder4Virtual(null, decPrice, tableid, decAll, decZ);
            //付款信息
            PosOrderBalDto posOrderBalDto = orderBusiness.CreateCashBal(tableid, -decPrice, -decPrice);
            HeadOrderInfo.billBal = new List<PosOrderBalDto>() { posOrderBalDto };
            HeadOrderInfo.billLine = new List<PosOrderLineDto>();
            var rs = await OrderApiUtil.SendOrderAsync(HeadOrderInfo);
            return rs;

        }
    }
}